﻿using MediatR;
using T.Vehicleservice.Domain.Dtos;
using T.Vehicleservice.Domain.T.MaintenanceRecord.Model;
using T.Vehicleservice.Read.API.Application.Command.MaintenancesRecordCommand;
using T.Vehicleservice.Repository.Interface;

namespace T.Vehicleservice.Read.API.Application.CommandHandlers.MaintenancesRecordCommandHander
{
    /// <summary>
    /// 显示保养信息
    /// </summary>
    public class MaintenanceRecordListCommandHander : IRequestHandler<MaintenanceRecordListCommand, PageDto<MaintenancesRecord>>
    {
        private readonly IMaintenanceRecordRepository _maintenanceRecordRepository;
        public MaintenanceRecordListCommandHander(IMaintenanceRecordRepository managementRecordRepository)
        {
            _maintenanceRecordRepository = managementRecordRepository;
        }
        public async Task<PageDto<MaintenancesRecord>> Handle(MaintenanceRecordListCommand request, CancellationToken cancellationToken)
        {
            PageDto<MaintenancesRecord> pageDto = new PageDto<MaintenancesRecord>();
            var MaintenancesRecordList = await _maintenanceRecordRepository.GetAsync(d => !d.IsDeleted);
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                MaintenancesRecordList = MaintenancesRecordList.Where(d => d.CompanyID == request.CompanyID).ToList();
            }
            if (!string.IsNullOrEmpty(request.MaintenanceHead))
            {
                MaintenancesRecordList= MaintenancesRecordList.Where(d=>d.MaintenanceHead.Contains(request.MaintenanceHead)).ToList();
            }
            if (request.CurrentMileageDate != null)
            {
                MaintenancesRecordList= MaintenancesRecordList.Where(d=>d.CurrentMileageDate==request.CurrentMileageDate).ToList();
            }
            if (!string.IsNullOrEmpty(request.LicensePlateNumber))
            {
                MaintenancesRecordList= MaintenancesRecordList.Where(d=>d.LicensePlateNumber.Contains(request.LicensePlateNumber)).ToList();
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = MaintenancesRecordList.Count();
            }
            var size = request.PageSize;
            var index = request.PageIndex;
            pageDto.TotalCount = MaintenancesRecordList.Count();
            pageDto.PageCount = (int)Math.Ceiling(pageDto.PageCount * 1.0 / (int)size);
            pageDto.list = MaintenancesRecordList.OrderByDescending(d => d.CreatedDate).Skip(((int)index - 1) * (int)size).Take((int)size).ToList();
            return pageDto;
        }
    }
}
